<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\TokenEnum;
use app\service\token\TokenInterface;
use app\service\token\TokenService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

class RefreshTokenStatusWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('refresh_token_status_work');
        $this->setDescription('刷新token状态');
        $this->addArgument('media_id', Argument::REQUIRED, '媒体 1巨量  2快手  3金牛');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $mediaId = intval($input->getArgument('media_id'));
        $output->writeln('=======刷新token状态开始' . date('Y-m-d H:i:s', time()) . '=======');
        try {
            $service = TokenService::getInstance($mediaId);
            if (! $service instanceof TokenInterface) {
                $output->writeln('=======刷新token状态失败: 服务错误' . date('Y-m-d H:i:s', time()) . '=======');
            }
            $tokens = $service->getMediaAppTokens(TokenEnum::TOKEN_STATUS_OK);
            if ($tokens) {
                foreach ($tokens as $token) {
                    $isValid = $service->checkTokenStatus($token);
                    if (! $isValid) {
                        // 设置失效状态
                        $res = $service->updateTokenData($token, ['status' => TokenEnum::TOKEN_STATUS_FAIL]);
                        if (! $res) {
                            $output->writeln('=======更新token状态失败id:' . $token->getKey() . $service::getError(0) . date('Y-m-d H:i:s', time()) . '=======');
                        }
                        // 删除关系
                        $res = $service->delTokenAccount($token->getKey());
                        if (! $res) {
                            $output->writeln('=======删除token账户关系失败id:' . $token->getKey() . $service::getError(0) . date('Y-m-d H:i:s', time()) . '=======');
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            dump($e);
            $output->writeln('=======刷新token状态失败' . $e->getMessage() . date('Y-m-d H:i:s', time()) . '=======');
        }
        $output->writeln('=======刷新token状态结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }
}
